//
//  PhotoViewController.m
//  Brand
//
//  Created by Woody Yan on 4/25/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "config.h"
#import "Photo.h"
#import "AFGetData.h"
#import "PhotoViewController.h"
#import "PhotoDetailViewController.h"
#import "HMSegmentedControl.h"
#import "PhotoCollectionViewCell.h"
#import "SpringCollectionViewFlowLayout.h"
#import "UIImageView+WebCache.h" //SDWebImage
#import "Header.h"
#import "VipVC.h"
#import "LoginViewController.h"


static NSString * const reuseID = @"collectionViewCellReuseId";


@interface PhotoViewController ()  <UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong) HMSegmentedControl *segmentedControl;
@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong)  SpringCollectionViewFlowLayout *springFlowLayout; //iOS 7
@property (nonatomic,strong) UICollectionViewFlowLayout *flowLayout; // iOS 6
@property (nonatomic,strong) NSMutableArray *allPhotos;

@property (strong, nonatomic) NSString *baseURL;

@end

@implementation PhotoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.baseURL = [NSString stringWithFormat:@"%@wallpaper",API_BASE];
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [Common handleHeightWithIPhone5WithView:self.view];
    self.allPhotos = [NSMutableArray array];
    
	UIImage *background = [UIImage imageNamed:@"Layer.png"];
	self.view.backgroundColor = [UIColor colorWithPatternImage:background];
	
	UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	backBtn.frame = CGRectMake(0, 0, 44, 44);
	UIImage *back = [UIImage imageNamed:@"return.png"];
    [backBtn setImage:back forState:UIControlStateNormal];
	[backBtn addTarget:self action:@selector(popOut) forControlEvents:UIControlEventTouchUpInside];
    backBtn.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
	
	UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
	title.font = [UIFont systemFontOfSize:18];
	title.text = @"壁纸下载";
    title.backgroundColor = [UIColor clearColor];
	title.textColor = ColorWithHex(0XFFFFFF);
	title.textAlignment = NSTextAlignmentCenter;
	
	UIView *navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	navBar.backgroundColor = [UIColor clearColor];
	
	[navBar addSubview:backBtn];
	[navBar addSubview:title];
    [self drawNavTopContentView:navBar];
	
	
	// Segmented control
	
	CGFloat yDelta;
    
    if (!isiOS6) { yDelta = 20.0f; } else { yDelta = 0.0f;}
	
    self.segmentedControl = [[HMSegmentedControl alloc] initWithFrame:CGRectMake(0, 44 + yDelta,kScreen_Width, 44)];
    self.segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    self.segmentedControl.sectionTitles = @[@"最热", @"最新", @"随机"];
    self.segmentedControl.font = [UIFont systemFontOfSize:15];
    self.segmentedControl.backgroundColor = [UIColor clearColor];
    self.segmentedControl.selectionIndicatorHeight = 1.0f;
    self.segmentedControl.selectedSegmentIndex = 0;
    self.segmentedControl.textColor = ColorWithHex(0XFFFFFF);
    self.segmentedControl.selectedTextColor = RGB(60, 195, 198);
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleBox;
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    [self.segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
    
    
	//UICollectionView
    
    if (isiOS7) {
        self.springFlowLayout = [[SpringCollectionViewFlowLayout alloc] init];
        self.springFlowLayout.minimumInteritemSpacing = 1.0f;
        self.springFlowLayout.minimumLineSpacing = 1.0f;
        self.springFlowLayout.itemSize = CGSizeMake(106, 190);

    } else {
        self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
        self.flowLayout.minimumLineSpacing = 1.0f;
        self.flowLayout.minimumInteritemSpacing = 1.0f;
        self.flowLayout.itemSize = CGSizeMake(106,190);
    }
    
    self.collectionView= [[UICollectionView alloc] initWithFrame:CGRectMake (0, self.segmentedControl.bottom, 320, self.view.height - self.segmentedControl.bottom) collectionViewLayout: (isiOS7 ? self.springFlowLayout : self.flowLayout)];
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    
    UINib *cellNib = [UINib nibWithNibName:@"PaperCell" bundle:nil];;
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:reuseID];
    
    //[self.collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:reuseID];
    [self.view addSubview:self.collectionView];
    
    [self fetchDataWithURL:[self.baseURL stringByAppendingString:@"&tab=0"]];
    
}

#pragma mark - ViewControl Cycle

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}

- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (isiOS7) {
        [self.springFlowLayout invalidateLayout];
    } else {
        [self.flowLayout invalidateLayout];
    }
}

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

#pragma mark - Segment Control


- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl
{
    [self.collectionView setContentOffset:CGPointMake(0, 0) animated:YES];
    switch (self.segmentedControl.selectedSegmentIndex)
    {
        // Input URL and then Fetch Data
        case 0: {
            [self fetchDataWithURL:[self.baseURL stringByAppendingString:@"&tab=0"]];
            break;
        }
        case 1: {
            [self fetchDataWithURL:[self.baseURL stringByAppendingString:@"&tab=1"]];
            break;
        }
        case 2: {
            [self fetchDataWithURL:[self.baseURL stringByAppendingString:@"&tab=2"]];
            break;
        }
        default:
            break;
    }

}


#pragma mark - Fetch Data


- (void) fetchDataWithURL:(NSString *) requestUrl
{
    [kApp displayWaitViewWithAllMaskView:NO];
    
    [[AFGetData sharedInstance] startGet:requestUrl
                         andResultIsJSON:YES
                               andCompletion:^(AFHTTPRequestOperation *operation, id responseObj, BOOL isSuccess)
        {
        if (isSuccess) {
            
            [kApp hideWaitView];
            
            NSArray * array = responseObj;
            [self.allPhotos removeAllObjects];
            for (NSDictionary *item in array){
               Photo *obj = [[Photo alloc] initWithType:[item objectForKey:@"type"]
                                               thumbUrl:[item objectForKey:@"thumb_pic"]
                                               largeUrl:[item objectForKey:@"pic"]
                                                mId:[item objectForKey:@"id"]
                             ];
            
               [self.allPhotos addObject:obj];
            }
            [self.collectionView reloadData];

        } else {
            [kApp hideWaitView];
            [PopTips tips:self.view Msg:NotifyNoNet];
            [self performSelector:@selector(popOut) withObject:self afterDelay:0.7];
        }
    }];
}


#pragma mark - UICollectionView Datasource

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
    return [self.allPhotos count];
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
     UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    UIImageView* trueImage = (UIImageView*)[cell viewWithTag:302];
    UIImageView* vipImage = (UIImageView*)[cell viewWithTag:303];
    
       Photo *photo = self.allPhotos[indexPath.item];
        NSURL *url = [NSURL URLWithString:photo.thumbUrl];
    
    

	[trueImage setImageWithURL:url
                   placeholderImage:nil
                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
          if (!error) {
             
              photo.thumbnail = image;
          }
        }
     ];
    if([photo.type isEqualToString:@"1"])
    {
        vipImage.hidden = NO;
    }
    else{
        vipImage.hidden = YES;
    }
     
	return cell;
    
}


#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Photo* photo = [self.allPhotos objectAtIndex:indexPath.row];
    if([photo.type isEqualToString:@"1"])
    {
        if([[UserObj sharedInstance] isLegalVip])
        {
            PhotoDetailViewController *photoDetailVC = [PhotoDetailViewController new];
            photoDetailVC.currentItemIndex = indexPath.row;
            photoDetailVC.dataArray = self.allPhotos;
            photoDetailVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:photoDetailVC animated:YES completion:nil];
            //[self.navigationController pushViewController:photoDetailVC animated:YES];
            return;
        }
        
        UIAlertView* alertView = [[UIAlertView alloc]initWithTitle:NotifyNormal message:@"诏书上还没有你的名字,请先升级VIP" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
       
        
    }
    else
    {
    
        PhotoDetailViewController *photoDetailVC = [PhotoDetailViewController new];
        photoDetailVC.currentItemIndex = indexPath.row;
        photoDetailVC.dataArray = self.allPhotos;
        photoDetailVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:photoDetailVC animated:YES completion:nil];
        //[self.navigationController pushViewController:photoDetailVC animated:YES];
    }
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex)
    {
        if([[UserObj sharedInstance] isLegalLogin])
        {
           //已经登录，但不是vip
            [kApp.rootNav popToRootViewControllerAnimated:NO];
             kApp.meHomeVC = [[MeHomeViewController alloc] initWithNibName:@"MeHomeViewController" bundle:nil];
            [kApp.rootNav pushViewController:kApp.meHomeVC animated:NO];
            VipVC* vipVC  =  [[VipVC alloc]initWithNibName:@"VipVC" bundle:nil];
            [kApp.rootNav pushViewController:vipVC animated:YES];
        }
        else{
            [kApp.rootNav popToRootViewControllerAnimated:NO];
            
             kApp.meHomeVC = [[MeHomeViewController alloc] initWithNibName:@"MeHomeViewController" bundle:nil];
            [kApp.rootNav pushViewController:kApp.meHomeVC animated:NO];
            
            LoginViewController* logVC = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
            [kApp.rootNav pushViewController:logVC  animated:YES];
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"%s",__PRETTY_FUNCTION__);
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
//    PhotoCollectionViewCell *ownCell = (PhotoCollectionViewCell *) cell;
//    [ownCell.imageView cancelCurrentImageLoad];
}


#pragma mark - Nav Pop

- (void) popOut{
    [kApp hideWaitView];
    [[AFGetData sharedInstance] removeAllGetAndPostRequest];
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
